package com.revzone.demo001.controller;

import com.revzone.demo001.config.JWTUtil_old;
import com.revzone.demo001.entity.User;
import com.revzone.demo001.entity.Result;
import com.revzone.demo001.entity.UserRoleDTO;
import com.revzone.demo001.entity.loginDTO;
import com.revzone.demo001.mapper.RoleMapper_old;
import com.revzone.demo001.mapper.UserMapper_old;
import com.revzone.demo001.service.UserService_old;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.core.annotation.AuthenticationPrincipal;
//import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/user")
//@Api(tags = "user用户管理", description = "用于user用户管理的相关API")
public class UserController_old {
    @Autowired
    UserService_old userService;
    @Autowired
    UserMapper_old userMapper;
    @Autowired
    RoleMapper_old roleMapper;

    private JWTUtil_old jwtTokenUtil; // JWT 工具类

    @PostMapping("/login")
    public Result login(@RequestBody loginDTO loginDTO) {
        User user = userService.authenticate(loginDTO.getUsername(), loginDTO.getPassword());
        if (user != null) {
            // 认证成功，生成 JWT Token
            String token = jwtTokenUtil.createToken(user.getUser_name());

            // 查询并返回用户的角色名列表和权限码列表
            List<String> roleNames = userMapper.findRoleNamesByUserId(user.getId());
            List<String> permissionCodes = userMapper.getUserPermissionCodes(user.getId()); // 获取所有权限码

            // 返回 Token 及其他用户基础信息
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", user.getId());
            data.put("username", user.getUser_name());
            data.put("nickname", user.getNick_name());
            data.put("role", roleNames);
            data.put("permission", permissionCodes); // 前端根据这些权限码来控制界面元素
            user.setStatus(1);
            // 这里通常还会返回用户的角色列表或权限标识符列表
            // userService.getUserRolesAndPermissions(user.getId());
            // data.put("roles", user.getRoles().stream().map(Role::getRoleName).collect(Collectors.toList()));
            // data.put("permissions", userService.getUserPermissionCodes(user.getId()));


            return Result.success(data); // R 是你的统一响应封装类
        } else {
            return Result.error(401, "用户名或密码错误");
        }
    }

    @PostMapping("/outLogin")
    public Result outLogin(@RequestBody(required = false) String username) {
        if (username == null || username.trim().isEmpty()) {
            return Result.error(400, "用户名不能为空");
        }
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        user.setStatus(0);
        boolean success = userService.updateById(user);
        return success ? Result.success("登出成功") : Result.error(500, "登出失败");
    }


    @GetMapping("/current")
    public Map<String, Object> getCurrentUser() {
        Subject currentUser = SecurityUtils.getSubject();

        Map<String, Object> info = new HashMap<>();
        info.put("authenticated", currentUser.isAuthenticated());
        info.put("principal", currentUser.getPrincipal());
        info.put("hasRoleAdmin", currentUser.hasRole("admin"));

        if (currentUser.getSession(false) != null) {
            info.put("sessionId", currentUser.getSession().getId());
            info.put("sessionTimeout", currentUser.getSession().getTimeout());
        }
        return info;
    }

    @PostMapping(value="/listwithrole", produces = "application/json;charset=UTF-8")
    public Result listResources(@RequestBody(required = false) User user ) {
        return Result.success(userMapper.getUserRolelist());
    }

    @RequiresPermissions("user:add")
    @PostMapping(value="/add", produces = "application/json;charset=UTF-8")
    @RequiresRoles("admin") // 只有 'admin' 角色才能访问
    public Result addResource(@RequestBody(required = false) UserRoleDTO userroleDTO) {
        //设置角色的时候新加user_role表
        return userService.saveUserWithRole(userroleDTO);
    }

    @RequiresPermissions("user:update")
    @PostMapping(value="/update", produces = "application/json;charset=UTF-8")
    @RequiresRoles("admin") // 只有 'admin' 角色才能访问
    public Result updateResource(@RequestBody(required = false) UserRoleDTO userroleDTO) {
        return userService.updateUserWithRole(userroleDTO);
    }

    @RequiresPermissions("user:delete")
    @GetMapping(value="/delete", produces = "application/json;charset=UTF-8")
    @RequiresRoles("admin") // 只有 'admin' 角色才能访问
    public Result deleteResource(@RequestParam(required = false) Integer id) {
        return userService.deleteUserWithRole(id);
    }

    //修改密码
    @RequiresRoles("admin")
    @PostMapping(value="/resetPassword", produces = "application/json;charset=UTF-8")
    public Result resetPassword(@RequestParam(required = false) Integer id, @RequestParam(required = false)String password) {
        return userService.resetPassword(id, password);
    }



}
